package com.qiyeji.real_estate.controller;

import com.qiyeji.real_estate.utils.Result;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Map;

@RequestMapping("/FileOperation")
@RestController
@ResponseBody
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Value("./FileSystem")
    private String uploadDir;

    @Value("./Files")
    private String downloadFiles;

    //在文件操作中，不用/或者\最好，推荐使用File.separator
    private final static String  fileDir="FileSystem";

    private  final static String rootPath = System.getProperty("user.dir") + File.separator+fileDir;

    @PostMapping("/deleteFile")
    public Result deleteFile(@RequestBody Map<String,String> params){
        uploadDir="./FileSystem";
        boolean flag=false;
        String fileName=params.get("fileName");
        System.out.println(uploadDir);
        File file = new File(uploadDir+fileName);
        System.out.println(file.getAbsolutePath());
        if(file.exists()){
            System.out.println("文件存在");
            flag=file.delete();
        }else{
            System.out.println("文件不存在");
        }
        if(flag==false) {
            System.out.println("删除失败");
            return Result.error();
        }
        else {
            System.out.println("删除成功");
            return Result.success(flag);
        }
    }

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            System.out.println("文件为空");
            return Result.error();
        }
        File tmp = new File(uploadDir);
        if (!tmp.exists() && !tmp.isDirectory()) {
            tmp.mkdirs();
            System.out.println("创建成功！");
        }
        try {
            //构建真实路径
            File newFile = new File(tmp.getAbsolutePath());
            //上传到绝对路径
            Path targetLocation=new File(newFile.getPath()+"\\"+file.getOriginalFilename()).toPath();
            System.out.println("targetLocation:"+targetLocation.toString());
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("上传成功");
            return Result.success("上传成功");
        } catch (IOException e) {
            System.out.println("上传失败"+e.getMessage());
        }
        return Result.error();
    }


    @PostMapping("/setFileStorageLocation")//设置上传路径
    public Result setFileStorageLocation(@RequestBody Map<String,String> params){
        uploadDir="./FileSystem";
        uploadDir=uploadDir+params.get("path");
        if(uploadDir==null) {
            return Result.error();
        }
        else {
            return Result.success(uploadDir);
        }
    }



    //    private final static String  fileDir="Download";
    //    @RequestParam String fileName
    //    private  final static String rootPath = System.getProperty("user.dir") + File.separator+fileDir+File.separator;
    @RequestMapping("/download")
    public Object downloadFile(@RequestParam String fileName, final HttpServletResponse response, final HttpServletRequest request){
        uploadDir="./FileSystem";
        OutputStream os = null;
        InputStream is= null;
        try {
            // 取得输出流
            os = response.getOutputStream();
            // 清空输出流
            String[] s=fileName.split("/");
            response.reset();
            response.setContentType("application/x-download;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ new String(s[s.length-1].getBytes("utf-8"), "iso-8859-1"));
            //读取流
            File f = new File(rootPath+fileName);
            is = new FileInputStream(f);
            if (is == null) {
                logger.error("下载附件失败，请检查文件“" + fileName + "”是否存在");
                return Result.error("下载附件失败，请检查文件“" + fileName + "”是否存在");
            }
            //复制
            IOUtils.copy(is, response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            return Result.error("下载附件失败,error:"+e.getMessage());
        }
        //文件的关闭放在finally中
        finally
        {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                logger.error(ExceptionUtils.getFullStackTrace(e));
            }
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                logger.error(ExceptionUtils.getFullStackTrace(e));
            }
        }
        return null;
    }

}
